package com.xywy.wjk.widget;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Paint.FontMetrics;
import android.graphics.Paint.Style;
import android.graphics.Path;
import android.graphics.PathEffect;
import android.graphics.Shader;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;

import com.xywy.wjk.bean.BloodPressureData;
import com.xywy.wjk.bean.WeightData;

/**
 * 折线图 view
 * 
 * @author wangwenlong
 * 
 */
public class BloodView extends View {
	// 假设的点集
	private int mWidth; // 屏幕宽度
	private int mHeight; // 屏幕高度
	private List<BloodPressureData> heighData; // 外部传进来高压值
	private int mode = -1; // 年 月 日 区分 外部传入
	public static final int MODE_WEEK = 1, MODE_DAY = 0, MODE_MOUNTH = 2,
			MODE_YEAR = 3; // 区分年月日
	private List<Float[]> heighPoints = new ArrayList<Float[]>(); // 折线图上面的点
	private List<Float[]> lowPoints = new ArrayList<Float[]>(); // 折线图上面的点

	private int mBottomHeight; // 底部线的高度
	private int mTextHeight = 40;

	private float mMaxLineHeight;
	private float mMinLineHeight;
	private int mLeftDistance; // 左边距
	private int mRightDistance; // 右边距

	private Paint valuePaint; // 最大最小值画笔
	private Paint textPain; // 日期画笔
	private Paint grayLinePain; // 灰色线画笔
	private Paint zxLinePaint; // 折线画笔
	private Paint whitePaint; // 白色
	private Paint dottedPaint; // 虚线
	private Paint pathPaint; // path

	private int minValue = 40; // 最小值是40公斤
	private int maxValue = 100; // 最大值是140公斤

	// private List<Long> timestmps;

	private Calendar calendar;

	private String timeStr[] = { "凌晨0点", "6", "中午12点", "18","24" };

	private String monthStr[] = new String[7];

	private String weekStr[] = new String[7];

	private String yearStr[];

	public BloodView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		// TODO Auto-generated constructor stub
		mWidth = 200;
		mHeight = 200;
		init();
	}

	public BloodView(Context context, AttributeSet attrs) {
		super(context, attrs);
		// TODO Auto-generated constructor stub
		mWidth = 200;
		mHeight = 200;
		init();
	}

	public BloodView(Context context) {
		super(context);
		// TODO Auto-generated constructor stub
		mWidth = 200;
		mHeight = 200;
		init();
	}

	// 初始化
	private void init() {
		calendar = Calendar.getInstance();
		// 最大最小值画笔
		valuePaint = new Paint();
		Typeface font = Typeface.create(Typeface.SANS_SERIF, Typeface.NORMAL);
		valuePaint.setTypeface(font);
		valuePaint.setTextSize(40);
		valuePaint.setColor(Color.GRAY);
		// 底部文字画笔
		textPain = new Paint();
		textPain.setTypeface(font);
		textPain.setTextSize(30);
		textPain.setColor(Color.BLACK);

		grayLinePain = new Paint(); // 设置画笔
		grayLinePain.setStrokeWidth(2);
		grayLinePain.setColor(Color.GRAY);
		grayLinePain.setStyle(Paint.Style.FILL);

		zxLinePaint = new Paint();
		zxLinePaint.setColor(0xfffe8f7d);
		zxLinePaint.setStrokeWidth(5);
		zxLinePaint.setStyle(Style.STROKE);

		whitePaint = new Paint();
		whitePaint.setColor(Color.WHITE);
		whitePaint.setStrokeWidth(2);
		whitePaint.setStyle(Paint.Style.FILL);

		// 画虚线
		dottedPaint = new Paint();
		dottedPaint.setStyle(Paint.Style.STROKE);
		dottedPaint.setStrokeWidth(2);
		dottedPaint.setColor(Color.GRAY);
		PathEffect effects = new DashPathEffect(new float[] { 5, 5, 5, 5 }, 1);
		dottedPaint.setPathEffect(effects);

		// path 画笔
		pathPaint = new Paint(); // 设置画笔
		pathPaint.setStrokeWidth(3);
		pathPaint.setStyle(Paint.Style.FILL);

	}

	@Override
	protected void onDraw(Canvas canvas) {
		// TODO Auto-generated method stub
		mBottomHeight = getMeasuredHeight() / 5;
		if (heighData != null) {
			mLeftDistance = (int) valuePaint.measureText("0000", 0, 4);
			mRightDistance = (int) textPain.measureText("00", 0, 2);
			mWidth = getMeasuredWidth() - mLeftDistance - mRightDistance;
			int viewWidth = getMeasuredWidth();
			mHeight = getMeasuredHeight() - mBottomHeight;
			float distance = (float) ((mWidth * 1.0) / 6); // 这个是通过点来平均下来每个点之间
															// 水平距离
			switch (mode) {
			case MODE_DAY:
				distance = (float) ((mWidth * 1.0) / 23);
				break;
			case MODE_MOUNTH:
				distance = (float) ((mWidth * 1.0) / 29);
				break;
			case MODE_WEEK:
				distance = (float) ((mWidth * 1.0) / 6);
				break;
			case MODE_YEAR:
				distance = (float) ((mWidth * 1.0) / 12);
				break;
			default:
				break;
			}

			float unitHeight = (float) (mHeight * 1.0 / (maxValue - minValue)); // 单位值
			heighPoints.clear();
			lowPoints.clear();
			canvas.drawColor(Color.WHITE);
			// 设置点
			float maxHeight = mHeight;
			long currentTime = System.currentTimeMillis();
			for (int i = 0; i < heighData.size(); i++) {
				if (heighData.get(i) == null)
					continue;
				Float[] heighPoint = new Float[2]; // 高压值
				Float[] lowPoint = new Float[2]; // 低压值
				Long l = heighData.get(i).getDate();
				calendar.setTimeInMillis(l);
				long hh = 0;

				switch (mode) {
				case MODE_DAY:
					hh = calendar.get(Calendar.HOUR_OF_DAY);
					break;
				case MODE_MOUNTH:
					// hh = calendar.get(Calendar.MONTH);
					hh = (currentTime - l) / (1000 * 60 * 60 * 24);
					break;
				case MODE_WEEK:
					hh = (currentTime - l) / (1000 * 60 * 60 * 24);
					break;
				case MODE_YEAR:
					Calendar current = Calendar.getInstance();
					int currentM = current.get(current.MONTH);
					int now = calendar.get(current.MONTH);
					hh = currentM - now;
					break;
				default:
					break;
				}

				if (mode != MODE_DAY) {
					heighPoint[0] = viewWidth - hh * distance - mRightDistance;
					lowPoint[0] = viewWidth - hh * distance - mRightDistance;
				} else {
					heighPoint[0] = hh * distance + mLeftDistance;
					lowPoint[0] = hh * distance + mLeftDistance;
				}
				float heighHeight = (float) ((heighData.get(i)
						.getHighPressure() - minValue) * unitHeight * 1.0);
				float lowHeight = (float) ((heighData.get(i).getLowPressure() - minValue)
						* unitHeight * 1.0);
				heighPoint[1] = (float) (mHeight - heighHeight);
				lowPoint[1] = (float) (mHeight - lowHeight);
				if (maxHeight > heighPoint[1])
					maxHeight = heighPoint[1];
				heighPoints.add(heighPoint);
				lowPoints.add(lowPoint);
			}

			// LinearGradient lg = new LinearGradient(0, maxHeight, 0, mHeight,
			// 0xfffe8f7d, Color.WHITE, Shader.TileMode.MIRROR);
			// pathPaint.setShader(lg);
			// //画渐变色
			// for (int i = 0; i < heighPoints.size() - 1; i++) {
			// Float point[] = heighPoints.get(i);
			// Float pointNext[] = heighPoints.get(i + 1);
			// Path tempPath = new Path();
			// tempPath.moveTo(point[0], mHeight);
			// tempPath.lineTo(point[0], point[1]);
			// tempPath.lineTo(pointNext[0], pointNext[1]);
			// tempPath.lineTo(pointNext[0], mHeight);
			// tempPath.close();
			// canvas.drawPath(tempPath, pathPaint);
			// }

			// 画线 折线
			for (int i = 0; i < (heighPoints.size() - 1); i++) {
				Float[] lPoint = heighPoints.get(i);
				Float[] rPoint = heighPoints.get(i + 1);
				canvas.drawLine(lPoint[0], lPoint[1], rPoint[0], rPoint[1],
						zxLinePaint);

				Float[] lowlPoint = lowPoints.get(i);
				Float[] lowrPoint = lowPoints.get(i + 1);
				canvas.drawLine(lowlPoint[0], lowlPoint[1], lowrPoint[0],
						lowrPoint[1], zxLinePaint);
			}

			// 画圆
			for (int i = 0; i < heighPoints.size(); i++) {
				Float[] point = heighPoints.get(i);
				canvas.drawCircle(point[0], point[1], 8, whitePaint);
				Float[] lowpoint = lowPoints.get(i);
				canvas.drawCircle(lowpoint[0], lowpoint[1], 8, whitePaint);
			}
			for (int i = 0; i < heighPoints.size(); i++) {
				Float[] point = heighPoints.get(i);
				canvas.drawCircle(point[0], point[1], 8, zxLinePaint);

				Float[] lowpoint = lowPoints.get(i);
				canvas.drawCircle(lowpoint[0], lowpoint[1], 8, zxLinePaint);
			}

			// 最小值虚线
			String minStr = "" + mMinLineHeight;
			String maxStr = "" + mMaxLineHeight;
			FontMetrics fm = valuePaint.getFontMetrics();
			float textHeight = fm.descent - fm.ascent;
			// 最大值实线
			canvas.drawLine(valuePaint.measureText(maxStr, 0, maxStr.length()),
					mHeight - (mMaxLineHeight - minValue) * unitHeight,
					getMeasuredWidth(), mHeight - (mMaxLineHeight - minValue)
							* unitHeight, grayLinePain);
			// 最大值 最小值 标注
			canvas.drawText(maxStr, 0, mHeight - (mMaxLineHeight - minValue)
					* unitHeight + textHeight / 4, valuePaint);

		}

		// 底部时间 和线
		drawBottom(canvas);
	}

	public void setGaveWorth(BloodPressureData[] heighData, int mode,
			WeightData[] lowData) {
		this.heighData = new ArrayList<BloodPressureData>();
		// 初始值 最高值
		for (int i = 0; i < heighData.length; i++) {
			BloodPressureData temp = heighData[i];
			if (temp != null) {
				this.heighData.add(temp);
				if (mMaxLineHeight < heighData[i].getHighPressure())
					mMaxLineHeight = heighData[i].getHighPressure();
				if (mMinLineHeight >= heighData[i].getHighPressure())
					mMinLineHeight = heighData[i].getHighPressure();
			}
		}

		Log.e("this.gaveWorth ", this.heighData.size() + "");
		mMinLineHeight = 400;
		mMaxLineHeight = 0;
		this.mode = mode;
		List<WeightData> temp = new ArrayList<WeightData>();
		for (int i = 0; i < weekStr.length; i++) {
			calendar.setTimeInMillis(System.currentTimeMillis()
					- (1000 * 60 * 60 * 24) * (6 - i));
			if (i == 0) {
				weekStr[i] = (calendar.get(Calendar.MONTH) + 1) + "月"
						+ calendar.get(Calendar.DAY_OF_MONTH) + "";
			} else {
				weekStr[i] = calendar.get(Calendar.DAY_OF_MONTH) + "";
			}
		}
		calendar = Calendar.getInstance();
		for (int i = monthStr.length - 1; i >= 0; i--) {
			if (i == monthStr.length - 1) {
				monthStr[i] = calendar.get(Calendar.DAY_OF_MONTH) + "";
				continue;
			} else if (i == 0) {
				calendar.add(Calendar.DAY_OF_MONTH, -5);
				monthStr[i] = (calendar.get(Calendar.MONTH) + 1) + "月"
						+ calendar.get(Calendar.DAY_OF_MONTH) + "";
			} else {
				calendar.add(Calendar.DAY_OF_MONTH, -5);
				monthStr[i] = calendar.get(Calendar.DAY_OF_MONTH) + "";
			}
		}
		calendar = Calendar.getInstance();
		int countmonth = calendar.get(Calendar.MONTH);
		yearStr = new String[countmonth + 1];
		for (int i = yearStr.length - 1; i >= 0; i--) {
			if (i == yearStr.length - 1) {
				yearStr[i] = (calendar.get(Calendar.MONTH) + 1) + "月";
			} else if (i == 0) {
				calendar.add(Calendar.MONTH, -1);
				yearStr[i] = calendar.get(Calendar.YEAR) + "年"
						+ (calendar.get(Calendar.MONTH) + 1) + "月";
			} else {
				calendar.add(Calendar.MONTH, -1);
				yearStr[i] = (calendar.get(Calendar.MONTH) + 1) + "月";
			}
		}

		invalidate();
	}

	private void drawBottom(Canvas canvas) {
		// 底部线和文字
		canvas.drawLine(0, getMeasuredHeight() - mBottomHeight,
				getMeasuredWidth(), getMeasuredHeight() - mBottomHeight,
				grayLinePain);
		switch (mode) {
		case MODE_DAY:
			int height = getMeasuredHeight();
			int distance = mWidth / (timeStr.length - 1);
			for (int i = 0; i < timeStr.length; i++) {
				// calendar.setTimeInMillis(timestmps.get(i));
				// String str = calendar.get(Calendar.HOUR_OF_DAY)+"";
				canvas.drawText(timeStr[i], distance * i + mLeftDistance
						- textPain.measureText(timeStr[i]) / 4, height
						+ mTextHeight - mBottomHeight, textPain);
			}
			break;
		case MODE_WEEK:
			int weekHeight = getMeasuredHeight();
			int weekDistance = mWidth / (weekStr.length - 1);
			for (int i = 0; i < weekStr.length; i++) {
				// calendar.setTimeInMillis(timestmps.get(i));
				// String str = calendar.get(Calendar.HOUR_OF_DAY)+"";
				canvas.drawText(weekStr[i], weekDistance * i + mLeftDistance
						- textPain.measureText(weekStr[i]) / 4, weekHeight
						+ mTextHeight - mBottomHeight, textPain);
			}
			break;
		case MODE_MOUNTH:
			int mounthHeight = getMeasuredHeight();
			int mounthDistance = mWidth / (monthStr.length - 1);
			for (int i = 0; i < monthStr.length; i++) {
				canvas.drawText(monthStr[i], mounthDistance * i + mLeftDistance
						- textPain.measureText(monthStr[i]) / 4, mounthHeight
						+ mTextHeight - mBottomHeight, textPain);
			}
			break;
		case MODE_YEAR:
			int yearHeight = getMeasuredHeight();
			int yearDistance = mWidth / (yearStr.length - 1);
			textPain.setTextSize(25);
			for (int i = 0; i < yearStr.length; i++) {
				if (i == 0) {
					canvas.drawText(yearStr[i], yearDistance * i
							+ mLeftDistance - textPain.measureText(yearStr[i])
							/ 2, yearHeight + mTextHeight - mBottomHeight,
							textPain);
				} else {
					canvas.drawText(yearStr[i], yearDistance * i
							+ mLeftDistance - textPain.measureText(yearStr[i])
							/ 4, yearHeight + mTextHeight - mBottomHeight,
							textPain);
				}
			}
			textPain.setTextSize(30);
			break;
		default:
			break;
		}
	}

	class weightComp implements Comparator<WeightData> {

		@Override
		public int compare(WeightData f, WeightData s) {
			// TODO Auto-generated method stub
			if (s != null && f != null) {
				long x = f.getDate();
				long y = s.getDate();
				if (x > y) {
					return 1;
				} else {
					return -1;
				}
			} else {
				return 0;
			}
		}

	}

}
